#include "includes/phrasecollection.h"
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>
#include <QtDebug>

// default constructor 
PhraseCollection::PhraseCollection() : QList<Phrase>() {

}

// parameterised constructor
PhraseCollection::PhraseCollection(const QString& filename) {
	fromXML(filename);
}

// conversion constructor for QList<Phrase>
PhraseCollection::PhraseCollection(const QList<Phrase>& other) {
	// use overloaded operator
	operator=(other);
}


void PhraseCollection::toXML(QString filename) const
{    
    QFile file(filename);
    file.open(QIODevice::WriteOnly);
    QTextStream outputStream(&file);
    this->toXML(outputStream);
}

void PhraseCollection::toXML(QTextStream& stream) const
{
    QDomDocument outputNode("");
    this->toXML(outputNode);
    outputNode.save(stream,0);
}

QDomNode PhraseCollection::toXML(QDomNode outputNode) const
{
    QDomDocument root = outputNode.ownerDocument();
    QDomElement node;

    if (this->size() > 1)
    {
        node = root.createElement("phrases");
        root.appendChild(node);
    } else node = outputNode.toElement();

    // save each phrase as a child node of 'node'
    foreach (Phrase p, *this)
    {
        p.saveToChild(node);
    }
    return node;
}

// load the entire phrase collection from an xml file.
// if directory given, then recursively load all phrases in directory.
// note that the Phrase* objects must be deleted
void PhraseCollection::fromXML(QString filename, QString category)
{
    QFileInfo fn;
    fn.setFile(filename);
    if (fn.isDir())
    {
        QStringList files = QDir(filename).entryList(QStringList("*.xml"));

        foreach (QString str, files)
            fromXML(filename + str);
        return;
    }

    QFile file(filename);
    file.open(QIODevice::ReadOnly);
    QDomDocument doc;

    QString error; int row, column;
    doc.setContent(&file, &error, &row, &column);

    QDomNodeList list = doc.elementsByTagName("phrase");
    if (! list.isEmpty())
    for (int i = 0; i < list.size(); i++)
    {
	// create a new phrase and add it to the collection.
	// note: memory must be freed
        Phrase temp;
        temp.loadFromNode(list.at(i));
        temp.setLesson(category);
        qDebug() << temp.getLesson();

        if (!this->contains(temp))
            this->append(temp);
        foreach (Phrase p, *this) {
            qDebug() << "lesson is " << p.getLesson();
        }
    }
}

// conversion from QList<Phrase*> to PhraseCollection
PhraseCollection& PhraseCollection::operator= (const QList<Phrase>& other) {
	// copy

	// clear this list
	clear();
	// add all items from other list
        foreach (Phrase p, other) {
		append(p);
	}
	return *this;
}
